import React, { useState, useMemo } from 'react';
import s from './style.module.css';
// import SelectAnt from '@/components/SelectAnt';
import {
  Table,
  Datetime,
  Button,
  Input,
  Tooltip,
  Pagination,
  Loading,
  Select
} from '@knownsec/react-component';
import moment from 'moment';
import { datetime } from '@/common/formatter';
import { warnList } from '~/API';
import { useLocation, Link } from 'react-router-dom';
import { GetQueryString } from '@/common/constant';
import cn from 'classnames';
import CopyText from '@/components/copy'

const task_type = {
  availability: '可用性',
  vul: '漏洞',
  securityEvent: '安全事件',
  risk_link: '风险外链',
  change_check: '篡改',
};

const defaultSearch = {
  task_type: null,
  time: [],
  target_name: '',
  target_group_name: '',
  page: 1,
  limit: 10,
};
export default function bugStore() {
  const [refe, setRef] = useState(false);
  const [showLoading, setShowLoading] = useState(true);
  const [searchInfo, setSearchInfo] = useState(defaultSearch);
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const search = useLocation().search;
  const name = GetQueryString(search, 'name');

  const columns = [
    {
      title: '业务系统',
      dataIndex: 'target_url',
      render: (e, row) => {
        let name = row.target_name ? row.target_name : row.target_title;
        return (
          <Tooltip
            overlay={
              <>
                <p>业务系统：<CopyText text={e}/></p>
                <p>业务系统名称：{name || '暂未设置'}</p>
              </>
            }
            placement="topLeft"
          >
            <div>
              {e}
              <div className={s.targetName} style={{ color: name ? '#000' : '#ccc' }}>
                {name || '--'}
              </div>
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '任务组',
      dataIndex: 'target_group_name',
      className: s.w_8,
      render:(e)=>{ 
        return (
          <Tooltip
            overlay={e}
            placement="topLeft"
          >
            <div className={s.targetName}>
              {e|| '--'}
            </div>
          </Tooltip>
        );}
    },
    {
      title: '监测项',
      dataIndex: 'task_type',
      className: s.w_8,
      render: (e) => {
        return <span>{task_type[e]}</span>;
      },
    },
    {
      title: '告警内容',
      dataIndex: 'content',
      className: s.w_16,
      render:(e)=>{return e||'--'}
    },
    {
      title: '告警时间',
      dataIndex: 'created_at',
      className: s.w_13,
      render: (e) => {
        return <span>{datetime(e)||'--'}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      className: s.w_8,
      valueType: 'option',
      render: (e, row) => {
        return (
          <a href={`/#/dashboard?sid=${row.task_session_id}&id=${row.target_id}&type=${row.task_type}`} target='_blank' rel="noreferrer">
            查看详情
          </a>
        );
      },
    },
  ];
  const disabledate = (current) => {
    return current > moment();
  };
  const getList = async (e) => {
    setShowLoading(true);
    setTableData({ data: [], total: 0 });
    const list = await warnList(e);
    if (list.status === 'success') {
        setTableData({ data: list.data.data, total: list.data.total });
        setShowLoading(false);
    }
  };
  const onSearch = (e) => {
    let params = { page: 1, limit: 10 };
    if (!e) {
      setSearchInfo(defaultSearch);
    } else {
      if (e.page) {
        setSearchInfo({ ...searchInfo, page: e.page, limit: e.limit });
        params = { ...searchInfo, page: e.page, limit: e.limit };
      } else {
        params = {
          ...searchInfo,
          ...params,
        };
      }
      if (searchInfo.time[0]) {
        let start_time = moment(searchInfo.time[0]._d).toJSON();
        let end_time = moment(searchInfo.time[1]._d).toJSON();
        params = {
          ...params,
          time_low: start_time,
          time_high: end_time,
        };
      } else {
        delete params.time;
      }
    }

    Object.keys(params).forEach((key) => {
      !params[key] && delete params[key];
    });
    getList(params);
  };
  React.useMemo(() => {
    if (name) {
      setSearchInfo({ ...searchInfo, keyword: name });
      getList({ page: 1, count: 10, keyword: name });
    } else {
      onSearch(true);
    }
  }, []);
  return (
    <div className={s.tableBox}>
      <div className={s.tool}>
        <Input
          pro
          value={searchInfo.target_name}
          search
          // clear
          onSearch={(e) => {
            onSearch({ wortarget_named: e.value });
          }}
          className={cn('inp', 'search-button')}
          placeholder="请输入业务系统名称"
          maxlength={32}
          autoComplete={'off'}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, target_name: e.value });
            e.value === '' && onSearch({ target_name: e.value });
          }}
        />
        <Input
          pro
          value={searchInfo.target_group_name}
          search
          // clear
          onSearch={(e) => {
            onSearch({ target_group_name: e.value });
          }}
          autoComplete={'off'}
          className="search-button inp"
          placeholder="请输入任务组名称"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, target_group_name: e.value });
            e.value === '' && onSearch({ target_group_name: e.value });
          }}
        />
        <Select
          pro
          value={[searchInfo.task_type]}
          placeholder="监测项"
          option={Object.entries(task_type).map(([type, val]) => {
            return { label: val, value: type };
          })}
          clearable
          className={s.sel}
          onChange={({ selectedItem }) => {
            const e = selectedItem[0]?.value || ''
            setSearchInfo({ ...searchInfo, task_type: e });
          }}
        />
        <Datetime
          disabledDate={disabledate}
          className={cn(s.radiu)}
          value={searchInfo.time}
          // showTime={false}
          onChange={(e) => {
            const e_ = e ? e : [];
            setSearchInfo({ ...searchInfo, time: e_ });
          }}
        />
        <Button
          pro
          type="primary"
          className={s.btn}
          onClick={() => {
            onSearch(true);
          }}
        >
          查询
        </Button>
        <Button
          pro
          onClick={() => {
            onSearch(false);
          }}
        >
          重置
        </Button>
      </div>
      <div className={s.tableDiv}>
        {/* <Loading show={showLoading} label="" /> */}
        <Table 
          refre={refe} 
          columns={columns} 
          className={s.table} 
          tableLoading={showLoading}
          loadingLabel=""
          data={tableData.data}></Table>
      </div>

      {tableData.total > 10 && <Pagination
        key={Number(123)}
        className={s.pagination}
        current={searchInfo.page}
        showQuickJumper={{ goButton: true }}
        showTotal={(total) => `共${total}条`}
        showSizeChanger={true}
        pageSize={searchInfo.limit}
        pageSizeOptions={['10', '20', '50']}
        total={tableData.total}
        onChange={(page, limit) => {
          onSearch({ page, limit });
        }}
      />}
    </div>
  );
}
